﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using DragonOgg.Interactive;

using OpenTK.Audio;

namespace ApocDev.TownsApi
{
    internal class Audio
    {
        // This is really just to enable OpenAL audio playback. This is just to ensure the CLR keeps a reference to it somewhere...
        // There's no need for anything else here :)
        private static AudioContext _imALittleTeaPotShortAndStout = new AudioContext();

        static Audio()
        {
            ParseAudioIni();
        }

        public static Dictionary<string, string> AudioDeclarations { get; set; }

        public static void PlaySoundFile(string file)
        {
            new AudioClip(AudioDeclarations[file]).Play();
        }

        private static void ParseAudioIni()
        {
            AudioDeclarations = new Dictionary<string, string>();
            string filePath = Path.Combine(Path.GetDirectoryName(ModFiles.BaseDirectory), "audio.ini");
            foreach (string line in File.ReadAllLines(filePath))
            {
                if (string.IsNullOrWhiteSpace(line))
                    continue;
                if (line.Trim().StartsWith("#"))
                    continue;

                string[] split = line.Split(new[] {"="}, StringSplitOptions.RemoveEmptyEntries);
                AudioDeclarations.Add(split[0], Path.Combine(ModFiles.BaseDirectory, "audio", split[1]));
            }
        }

        private static void Save()
        {
            var sb = new StringBuilder();
            foreach (var audioDeclaration in AudioDeclarations)
            {
                sb.AppendLine(audioDeclaration.Key + "=" + Path.GetFileName(audioDeclaration.Value));
            }
            File.WriteAllText(Path.Combine(ModFiles.ModifiedDirectory, "audio.ini"), sb.ToString());
        }
    }
}